<?php

/*
 * This file is part of ibrand/balance.
 *
 * (c) 果酱社区 <https://guojiang.club>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace GuoJiangClub\Component\Balance;

use Prettus\Repository\Eloquent\BaseRepository;

class BalanceRepository extends BaseRepository
{
    /**
     * Specify Model class name.
     *
     * @return string
     */
    public function model()
    {
        return Balance::class;
    }

    /**
     * get user's balance.
     *
     * @return int
     * */
    public function getSum($id, $type = null)
    {
        if (null !== $type) {
            $sum = $this->model->where([
                'user_id' => $id,
                'type' => $type,
            ])->sum();
        } else {
            $sum = $this->model->where('user_id', $id)->sumBalance();
        }
        if ($sum) {
            return $this->getSumNumeric($sum);
        }

        return 0;
    }

    public function fluctuation($user_id, $type = 'recharge')
    {
        /*return $this->model->where('user_id', $user_id)->where('type', $type)->orderBy('created_at','desc');*/
        if ('consume' == $type) { // 支出
            return $this->model->where('user_id', $user_id)->where('value', '<', 0)->orderBy('created_at', 'desc');
        }

        return $this->model->where('user_id', $user_id)->where('value', '>', 0)->orderBy('created_at', 'desc');
    }

    public function addRecord($arr)
    {
        return $this->model->create($arr);
    }

    private function getSumNumeric($sum)
    {
        if (!is_numeric($sum)) {
            return 0;
        }

        return (int) $sum;
    }
}
